var removeDataSourceId;// 要删除的DataSource的id
var updateSQLUploadId;
var checkEmailDDLTable;
var params = {
	pageSize : 10
};

$(document)
		.ready(
				function() {
					$("#userNameDiv").hide();
					$("#selectSqlTypeDiv").change(function(){
						if($("#sqlType option:selected").val() == 'e sql'){
							$("#userNameDiv").show();
						}else{
							$("#userNameDiv").hide();
						}
					});
					cancelDBAExecOpt();
					isShowType();
					lookLinkBtn();
					lookDetailContent();
					searchDetailContent();
					/*codemirrorSqlHint();*/
					// 操作按钮
					LTS.colFormatter.optFormat = function(v, row) {
						if (v == 0) {
							if(row.sqlType == 'e sql'){
								return generateAppOptCommitOaButtons(row);
							}else if(row.sqlType == 'd sql'){
								return generateDBAOptButtons(row);
							}else{
								return generateAppOptButtons(row);
							}
						}else if(v==64 || v==32){
							return generateAppNewExecSuccessOptButtons(row);
						} else {
							return generateAppNewOptButtons(row);
						}

					}
					// 空
					LTS.colFormatter.emptyString = function(v, row) {
						return emptyString(v);
					}
					// 上传类型
					LTS.colFormatter.uploadTypeFormat = function(v, row) {
						return uploadTypeFormatName(row);
					}

					LTS.colFormatter.astatusFormat = function(v, row) {
						return astatusFormatName(row);
					}

					checkEmailDDLTable = $("#email-check-table")
							.ltsTable(
									{
										url : getUrlBySuffix("/sqlupload/findSqlUploadDataPost"),
										templateId : 'email-check-table-template'
									});

					checkEmailDDLTable.post(params, 1);

					clickCommitEmailBtn();
					clickRemoveBtn();
					clickConfirmRemoveBtn();
					clickUpdateBtn();
					removeFiles();
					clickLookProgressBtn();// 查看进度

					var paramJson = {};
					$(document)
							.on(
									"blur",
									".form-group",
									function() {
										paramJson['adId'] = $(
												"#databaseName option:selected")
												.val();
										paramJson['sqlType'] = $(
												"#sqlType option:selected")
												.val();
										paramJson['uploadType'] = $(
												"#sqlUploadType option:selected")
												.val();
										paramJson['project'] = $(
												"#projectSelected option:selected")
												.val();
										paramJson['dbName'] = $(
												"#databaseName option:selected")
												.attr("dbname");
										paramJson['dbType'] = $("#databaseName option:selected").attr("dbtype");
										paramJson['id'] = updateSQLUploadId;
										paramJson['userName'] = $("#userName").val();
									});

					$("#sql-upload-form").ajaxForm(
							{
								url : getRoot()
										+ '/sqlupload/updateSqlUploadById',
								beforeSubmit : function() {
									if ($("#databaseName").val() == '0') {
										swal("警告", "请选择数据库或者添加数据库", "warning");
										return false;
									}
									var email = $("#email").val();
									if (!$("#email").val()) {
										swal("警告", "邮箱名不能为空", "warning");
										return false;
									}
									var emailReg = new RegExp(LTS.ReExp.email);
									var emailArray = email.split(',');
									for(var i in emailArray){
										var em = emailArray[i];
										if (!emailReg.test($.trim(em))) {
											swal("警告", "部门负责人邮箱格式不正确，正确格式为：xxx@gomeplus.com", "warning");
											return false;
										}
									}
									if ($("#sqlUploadType option:selected").val() == 'file') {
										if (!$("#fileName").html()) {
											swal("警告", "请上传文件，否则选择文本模式上传","warning");
											return false;
										}
									}
									if (!$.trim($("#sqlText").val())) {
										swal("警告", "请填写SQL文本", "warning");
										return false;
									}
									if (!$("#usages").val()) {
										swal("警告", "请填写SQL使用说明", "warning");
										return false;
									}
									if($("#sqlType option:selected").val() == 'e sql'){
										var userName = $("#userName").val();
										if(isEmpty(userName)){
											swal("警告","申请人不能为空","warning");
									        return false;
										}
										var ZN_NameReg = new RegExp(LTS.ReExp.ZnName);
										var result = userName.match(ZN_NameReg);
										if(null==result || 0==result.length){
											swal("警告","请输入中文姓名","warning");
									        return false;
										}
									}
								},
								data : paramJson,
								dataType : 'json',
								resetForm : false,
								success : function(data) {
									if (data.success) {
										swal({
											title : "操作成功",
											text : data['message'],
											type : "success"
										}, function() {
											var param = {
												pageSize : 10
											};
											checkEmailDDLTable.post(param,
													pageNum);
											$("#email-check-edit-modal").modal(
													"hide");
										});
										return true;
									}
									if (!data.failure) {
										swal("失败", data.message, "error");
										return false;
									}
								}
							});

});

// 上传类型 名称
function uploadTypeFormatName(data) {
	var uploadTypeName = data['uploadType'];
	if (uploadTypeName == 'text') {
		return "文本";
	}
	if (uploadTypeName == 'file') {
		return "附件";
	}
}

/**
 * 查询状态名称
 */
function astatusFormatName(data) {
	var statusInt = data['astatus'];
	return switchStatus(statusInt);
}
function switchStatus(statusInt) {
	statusInt = $.trim(statusInt);
	var statusName;
	switch (statusInt) {
	case "0":
		statusName = "待提交";
		break;
	case "2":
		statusName = "待批准";
		break;
	case "4":
		statusName = "批准未通过";
		break;
	case "8":
		statusName = "已批准";
		break;
	case "16":
		statusName = "DBA执行中";
		break;
	case "32":
		statusName = "执行失败";
		break;
	case "64":
		statusName = "执行成功";
		break;
	case "128":
		statusName = "作废";
		break;
	}
	return statusName;
}
function generateAppOptButtons(data) {
	var optButtons = "" + updateBtn + removeBtn
			+ '<a href="javascript:;" class="commitEmail-btn">'
			+ '<span class="label label-success" style="font-size: 14px">'
			+ '<i class="fa fa-eye"></i>&nbsp;&nbsp;' + '待提交给负责人' + '</span>'
			+ '</a>&nbsp;';
	return optButtons;
}
function generateDBAOptButtons(data) {
	var optButtons = "" + updateBtn + removeBtn
			+ '<a href="javascript:;" class="commitEmail-btn">'
			+ '<span class="label label-success" style="font-size: 14px">'
			+ '<i class="fa fa-eye"></i>&nbsp;&nbsp;' + '待提交给DBA' + '</span>'
			+ '</a>&nbsp;';
	return optButtons;
}
function generateAppOptCommitOaButtons(data){
	var optButtons = "" + updateBtn + removeBtn
	+ '<a href="javascript:;" class="commitEmail-btn">'
	+ '<span class="label label-success" style="font-size: 14px">'
	+ '<i class="fa fa-eye"></i>&nbsp;&nbsp;' + '待提交OA' + '</span>'
	+ '</a>&nbsp;';
return optButtons;
}
function generateAppNewOptButtons(data) {
	var optButtons = ""
			+ '<a href="javascript:;" class="">'
			+ '<span class="label label-success" style="font-size: 14px">'
			+ '<i class="fa fa-zidingyi"></i>&nbsp;&nbsp;' + '已提交' + '</span>'
			+ '</a>&nbsp;' 
			+ '<a href="javascript:;" class="detailCommentBtn">'
			+ '<span class="label label-success" style="font-size: 14px">'
			+ '<i class="fa fa-road"></i>&nbsp;&nbsp;' 
			+ '详细内容' 
			+ '</span></a>&nbsp;'
			+ '<a href="javascript:;" class="lookProgressBtn">'
			+ '<span class="label label-success" style="font-size: 14px">'
			+ '<i class="fa fa-eye"></i>&nbsp;&nbsp;' 
			+ '查看进度' 
			+ '</span></a>&nbsp;'
			+ '<a href="javascript:;" class="cancelDBAExecBtn">'
			+ '<span class="label label-success" style="font-size: 14px">'
			+ '<i class="fa fa-gear"></i>&nbsp;&nbsp;' 
			+ '作废' 
			+ '</span></a>&nbsp;';
	return optButtons;
}
function generateAppNewExecSuccessOptButtons(data) {
	var optButtons = "" 
			+ '<a href="javascript:;" class="">'
			+ '<span class="label label-success" style="font-size: 14px">'
			+ '<i class="fa fa-zidingyi"></i>&nbsp;&nbsp;' + '已提交' + '</span>'
			+ '</a>&nbsp;' 
			+ '<a href="javascript:;" class="detailCommentBtn">'
			+ '<span class="label label-success" style="font-size: 14px">'
			+ '<i class="fa fa-road"></i>&nbsp;&nbsp;' 
			+ '详细内容' 
			+ '</span></a>&nbsp;'
			+ '<a href="javascript:;" class="lookProgressBtn">'
			+ '<span class="label label-success" style="font-size: 14px">'
			+ '<i class="fa fa-eye"></i>&nbsp;&nbsp;' 
			+ '查看进度' 
			+ '</span></a>&nbsp;'
			+ '<a href="javascript:;" class="lookLinkResultBtn">'
			+ '<span class="label label-success" style="font-size: 14px">'
			+ '<i class="fa fa-search"></i>&nbsp;&nbsp;' 
			+ '查看结果' 
			+ '</span></a>&nbsp;';
	return optButtons;
}

/**
 * 点击发送邮件按钮
 */
function clickCommitEmailBtn() {
	$(document).on(
			"click",
			".commitEmail-btn",
			function() {
				var id = getCurrentId($(this));
				var DBAUrl = getRoot() + '/sqlupload/commitDBAInterfaceData';
				$("#datasourceLoadingGenerator").modal("show");
				$.post(DBAUrl, {
					"SQLUPMId" : id
				}, function(data) {
					if (data.success) {
						var json = readHttpSendEmailJsonpInterface(data.params,
								data.ip, id,data.sqlType);
					} else {
						if (!data.success) {
							$("#datasourceLoadingGenerator").modal("hide");
							swal("错误", data.info + "", "error");
						}
					}
				});
			});
}

/**
 * 点击删除按钮
 */
function clickRemoveBtn() {
	$(document).on("click", ".remove-btn", function() {
		removeDataSourceId = getCurrentId($(this));
		$("#remove-tip-modal").modal("show");
	});
}

/**
 * 点击确认删除按钮
 */
function clickConfirmRemoveBtn() {
	$(document).on(
			"click",
			"#confirm-remove-btn",
			function() {
				$("#cancel-remove-btn").trigger("click");// 提示框隐藏
				var params = {};
				params['id'] = $.trim(removeDataSourceId);
				$.postHttp(params,
						getUrlBySuffix("/sqlupload/removeSqlUploadData"),
						function(json) {
							if (json.success) {
								swal({
									title : "操作成功",
									text : json['message'],
									type : "success"
								}, function() {
									var param = {
										pageSize : 10
									};
									checkEmailDDLTable.post(param, 1);
									$("#email-check-edit-modal").modal("hide");
								});
							} else {
								swal("错误", json.message + "", "error");
								return;
							}

						});
			});
}

/**
 * 点击更新按钮
 */
function clickUpdateBtn() {
	$(document).on(
			"click",
			".update-btn",
			function() {
				updateSQLUploadId = getCurrentId($(this));
				var url = getRoot() + '/sqlupload/findSingleBeanSqlUpload';
				var params = {};
				params['id'] = updateSQLUploadId;
				$.postHttpSync(params, url, function(json) {
					if (json && json.success) {
						var list = json['list'];
						params = list[0];
					} else {
						if (json) {
							swal('失败', json['message'], 'error');
							return;
						}
					}
				});
				$("#fileName").empty();
				$("#fileName").html(params['files']);
				$.each($('#sql-upload-form').parent().find(".form-control"),
						function() {
							var name = $(this).attr("name");
							if (isNull(name)) {
								return true;
							}
							name = $.trim(name);
							if (name == 'adId') {
								$("#databaseName").val(params[name]);
								$("#databaseName").selectpicker('refresh');
							}
							$(this).val(params[name]);
							if(name == 'email'){
								$(this).val(params['auserEmail']);
							}
							if(name == 'project')$("#projectSelected").selectpicker('refresh');
							if(name == 'uploadType')$("#sqlUploadType").selectpicker('refresh');
							$("#"+name).selectpicker('refresh');
						});
				if($("#sqlType option:selected").val() == 'e sql'){
					$("#userNameDiv").show();
				}else{
					$("#userNameDiv").hide();
				}
				if ($("#sqlUploadType option:selected").val() == 'text') {
					$("#sqlFileBlockd").hide();
				}
				if ($("#sqlUploadType option:selected").val() == 'file') {
					$("#sqlFileBlockd").show();
				}
				$("#email-check-edit-modal").modal("show");
			});
}

function isShowType() {
	$("#blockServeiceIPAddr").change(function() {
		if ($("#sqlUploadType option:selected").val() == 'text') {
			$("#sqlFileBlockd").hide();
		}
		if ($("#sqlUploadType option:selected").val() == 'file') {
			$("#sqlFileBlockd").show();
		}
	});
}

function removeFiles() {
	$(document).on("#removeBtn", "click", function() {
		$("#sqlFile1").parents().remove();
	});
}

function clickLookProgressBtn() {
	$(document)
			.on(
					"click",
					".lookProgressBtn",
					function() {
						var url = getRoot()
								+ '/sqlupload/findStatusCheckProgress';
						var params = {};
						params['sqlId'] = getCurrentId($(this));
						var statusLists = new Array();
						$
								.post(
										url,
										params,
										function(data) {
											if (data.success) {
												statusLists = data.sqlRecordLists;
												var tableStart = "<table class='table table-stripped toggle-arrow-tiny footable' data-page-size='100' style='font-size: 14px'>"
														+ "<thead><tr><th>id</th><th>DBA处理状态</th><th>处理时间</th><th>执行信息</th><th>负责人审核状态</th><th>审核时间</th>"
														+ "<th>审核信息</th></tr></thead><tbody>";
												var tableContent = "";

												if (statusLists.length == 0) {
													tableContent += "<tr><td colspan='7'>暂无数据</td></tr>";
												} else {
													for ( var i in statusLists) {
														var dealStatus = switchStatus(statusLists[i].dealStatus);
														var checkStatus = switchStatus(statusLists[i].checkStatus);
														var dealTime;
														if (!statusLists[i].dealTime) {
															dealTime = "暂无";
														} else {
															dealTime = statusLists[i].dealTime;
														}
														var dbaMsg;
														if (!statusLists[i].dbaMsg) {
															dbaMsg = "暂无";
														} else {
															dbaMsg = statusLists[i].dbaMsg;
														}
														var checkTime;
														if (!statusLists[i].checkTime) {
															checkTime = "暂无";
														} else {
															checkTime = statusLists[i].checkTime;
														}
														var checkMsg;
														if (!statusLists[i].checkMsg) {
															checkMsg = "暂无";
														} else {
															checkMsg = statusLists[i].checkMsg;
														}
														if (!dealStatus) {
															dealStatus = "暂无";
														}
														if (!checkStatus) {
															checkStatus = "暂无";
														}
														var tdHtml = "<tr><td class='id-tr'><span class='id-span'>"
																+ statusLists[i].id
																+ "</span></td>"
																+ "<td>"
																+ dealStatus
																+ "</td><td>"
																+ dealTime
																+ "</td>"
																+ "<td>"
																+ dbaMsg
																+ "</td><td>"
																+ checkStatus
																+ "</td><td>"
																+ checkTime
																+ "</td>"
																+ "<td>"
																+ checkMsg
																+ "</td>";
														tableContent += tdHtml
																+ "</tr>";
													}
												}

												var tableEnd = "</tbody></table>"

												var tableHtml = tableStart
														+ tableContent
														+ tableEnd;

												$("#checkStatusTable").empty();
												$("#checkStatusTable").append(
														tableHtml);
												$("#check-status-modal").modal(
														"show");
											} else {
												if (data.failure) {
													swal("失败", data.msg,
															"error");
													return;
												}
											}
										});
					});
}

/**
 * 发送邮件之前，先调取DBA接口，执行成功发送邮件，执行失败，不发送邮件
 * sqlType : 
 * e sql : 代表发送OA审批
 * d sql : 代表直接发送DBA审批
 * 其余 sql 类型发送邮件审批
 */
function readHttpSendEmailJsonpInterface(params, ip, id,sqlType) {
	$.ajax({
		type : "POST",
		async : true,
		url : "http://" + ip + "/mcenter/websql/api/sqlupload",
		data : {
			pargs : params
		},
		dataType : 'jsonp',
		jsonp : 'callbackparam',
		jsonpCallback : "success_jsonpCallback",
		success : function(json) {
			var state = json[0];
			if (state.toLowerCase() == 'ok') {
				if(sqlType == 'e sql'){
					sendOA(id);
				}else if(sqlType == 'd sql'){
					sendDBAUpdateStatus(id);
				}else{
					sendEmail(id);
				}
			} else {
				if (state.toLowerCase() == 'error') {
					$("#datasourceLoadingGenerator").modal("hide");
					swal("接口异常", json[1].substring(0,500) + "...", "error");
					return;
				}
			}
		}
	});
}
/**
 * 发送DBA更新状态
 * */
function sendDBAUpdateStatus(id){
	var url = getRoot() + '/sqlupload/updateSQLUploadStatus';
	$.post(url,{"sqlUpId":id},function(data){
		$("#datasourceLoadingGenerator").modal("hide");
		if (data.success) {
			swal({
				title : "操作成功",
				text : '成功',
				type : "success"
			}, function() {
				var param = {
					pageSize : 10
				};
				checkEmailDDLTable.post(param, pageNum);
				$("#email-check-edit-modal").modal("hide");
			});
		}
		if (!data.success) {
			$("#datasourceLoadingGenerator").modal("hide");
			swal("错误", data.msg + "", "error");
			return;
		}
	});
}
/**
 * 发送邮件
 */
function sendEmail(id) {
	var url = getRoot() + '/sqlupload/ajaxCommitEmailInterface';
	$.post(url, {
		"SQLUPMId" : id
	}, function(data) {
		$("#datasourceLoadingGenerator").modal("hide");
		if (data.success) {
			swal({
				title : "操作成功",
				text : data['message'],
				type : "success"
			}, function() {
				var param = {
					pageSize : 10
				};
				checkEmailDDLTable.post(param, pageNum);
				$("#email-check-edit-modal").modal("hide");
			});
		}
		if (!data.success) {
			$("#datasourceLoadingGenerator").modal("hide");
			swal("错误", data.message + "", "error");
			return;
		}
	});
}
/**
 * sendOA 发送OA接口
 * */
function sendOA(id){
	var url = getRoot()+'/sqlupload/commitOAInterfaceData';
	$("#datasourceLoadingGenerator").modal("hide");
	$.post(url,{"sqlOaCmId":id},function(data){
		if(data.success){
			$("#datasourceLoadingGenerator").modal("hide");
			swal({
				title : "执行成功",
				text : '已提交申请人OA系统,请到OA中填写审批流程负责人！',
				type : "success"
			}, function() {
				var param = {
					pageSize : 10
				};
				checkEmailDDLTable.post(param, pageNum);
				$("#email-check-edit-modal").modal("hide");
			});
		}else{
			if(!data.success){
				$("#datasourceLoadingGenerator").modal("hide");
				swal("错误", data.msg + "", "error");
			}
		}
	});
}
//作废
function cancelDBAExecOpt(){
	$(document).on("click",".cancelDBAExecBtn",function(){
		var id = getCurrentId($(this));
		var url = getRoot() + '/sqlupload/cancelSqlUploadById';
 		$.post(url,{"id":id},function(data){
 			if(data.success){
 				swal({
 					title : "处理成功",
 					text : data.message,
 					type : "success"
 				}, function(){
 					var param = {
 						pageSize : 10
 					};
 					checkEmailDDLTable.post(param, pageNum);
 					$("#email-check-edit-modal").modal("hide");
 				});
 			}else{
 				swal("处理失败",data.message,"error");
 			}
 		});
	});
}
/**
 * 查看链接
 * */
function lookLinkBtn(){
	$(document).on("click",".lookLinkResultBtn",function(){
		var id = getCurrentId($(this));
		var astatus = $(this).parent().parent().find(".dataStatus").val();
		var url = getRoot() + '/sqlupload/lookLinkSqlUpRecord';
		$.post(url,{"id":id,"status":astatus},function(data){
			if(data.success){
				window.open(data.result);
			}else{
				swal("警告",data.result,"warning");
			}
		});
	});
}
/**
 * 搜索
 */
function searchDetailContent(){
	$(document).on("click","#searchBtn",function(){
		var commitUserEmail = $("#commitUserEmail").val();
		var startTime = $("#startDatetime").val();
		var endTime = $("#endDatetime").val();
		debugger;
		var usages = $("#commitUsages").val();
		var astatus = $("#sqlAstatus").val();
		var params = {'commitUserEmail':commitUserEmail,'startTime':startTime,'endTime':endTime,'usages':usages,'astatus':astatus};
		checkEmailDDLTable.post(params,1);
	});
}
/**
 * 查看详细内容
 */
function lookDetailContent(){
	$(document).on("click",".detailCommentBtn",function(){
		var id = getCurrentId($(this));
		var url = getRoot() + '/sqlupload/findSingleBeanSqlUpload';
		var params = {};
		params['id'] = id;
		$.post(url,params,function(data){
			if(data.success){
				var obj = data.list;
				obj = obj[0];
				$("#searchSqlText").val(obj.sqlText);
				$("#searchSqlBackup").val(obj.sqlBackup);
				$("#sqlUpload-search-modal").modal("show");
			}else{
				swal('失败',data.message,'error');
			}
		});
	});
}